package com.itHaipeng.service.impl;

import com.itHaipeng.factory.SqlSessionFactoryUtil;
import com.itHaipeng.mapper.BrandMapper;
import com.itHaipeng.object.Brand;
import com.itHaipeng.service.IService;
import com.itHaipeng.utils.PageBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class IServiceImpl implements IService {
    private static final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();
        return brands;
    }

    @Override
    public void insert(Brand brand) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.insert(brand);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteByIds(int[] ids) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteByIds(ids);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public PageBean<Brand> selectByPage(int begin, int size) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectByPage(begin, size);
        PageBean<Brand> pageBean=new PageBean<>();
        int i = mapper.totalNumber();
        pageBean.setRows(brands);
        pageBean.setTotalCount(i);
        return pageBean;
    }

    @Override
    public PageBean<Brand> selectByPageCondition(int begin,int size,Brand brand) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectByPageCondition(begin, size, brand);
        int total = mapper.total(brand);
        PageBean<Brand> pageBean=new PageBean<>();
        pageBean.setTotalCount(total);
        pageBean.setRows(brands);
        return pageBean;
    }
     @Override
    public void upData(Brand brand) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.upData(brand);
        sqlSession.commit();
        sqlSession.close();
    }
}
